package com.honeywen.mymvc.leetcode;


/**
 * 24. 两两交换链表中的节点
 * https://leetcode-cn.com/problems/swap-nodes-in-pairs/
 *
 * @author wangwei
 * @date 2019/4/28
 */
public class SwapPairsTest {


    public static ListNode swapPairs(ListNode head) {

        ListNode prev = new ListNode(0);
        prev.next = head;
        head = prev;

        ListNode node = prev.next;




        while (node != null && node.next != null) {
            // 保存三个
            ListNode first = node;
            ListNode second = node.next;
            ListNode third = node.next.next;

            prev.next = second;
            first.next = third;
            second.next = first;

            prev = node;
            node = node.next;
        }



        return head.next;

    }


    private static void print(ListNode node) {
        System.out.println();
        while (node != null) {
            System.out.print(node.val + "->");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        print(node1);

        print(swapPairs(node1));


    }

}
